<template>
  <div class="sidebar" v-if="visible">
    <div class="sidebar-header">
      <h3>笔记</h3>
      <button class="new-file-btn" @click="createNewFile" title="新建文件">
        <span class="icon">+</span>
      </button>
    </div>
    <div class="file-list">
      <div 
        v-for="file in files" 
        :key="file.path"
        class="file-item"
        :class="{ active: isActiveFile(file) }"
        @click="selectFile(file)"
        @contextmenu.prevent="showContextMenu($event, file)">
        <span class="file-name">{{ file.name }}</span>
        <span class="file-date">{{ formatDate(file.lastModified) }}</span>
      </div>
      
      <!-- 右键菜单 -->
      <div 
        v-if="contextMenuVisible"
        class="context-menu"
        :style="{ top: contextMenuY + 'px', left: contextMenuX + 'px' }">
        <div class="context-menu-item" @click="deleteFile(selectedFileForMenu)">
          <span class="icon">🗑️</span> 删除
        </div>
      </div>
      

    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { showConfirm } from '../composables/useModal.js'

const props = defineProps({
  visible: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['file-selected'])

const files = ref([])

const defaultDir = ref('')

// 右键菜单状态
const contextMenuVisible = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)
const selectedFileForMenu = ref(null)




const loadFilesFromDirectory = async () => {
  try {
    const fileList = await window.electronAPI.readDirectory(defaultDir.value)
    console.log('文件列表:', fileList.files)
    
    // 获取所有markdown文件
    const markdownFiles = fileList.files
      .filter(file => file.endsWith('.md'))
      .map(filename => ({
        filename,
        path: `${defaultDir.value}/${filename}`
      }))

    // 为每个文件读取第一行作为显示名称
    const filesWithNames = await Promise.all(
      markdownFiles.map(async (file) => {
        try {
          const [lineResult, statsResult] = await Promise.all([
            window.electronAPI.readFileFirstLine(file.path),
            window.electronAPI.getFileStats(file.path)
          ])
          
          return {
            name: lineResult.firstLine || file.filename.replace('.md', ''),
            type: 'file',
            path: file.path,
            filename: file.filename,
            lastModified: statsResult.success ? statsResult.stats.mtime : new Date()
          }
        } catch (error) {
          console.error(`读取文件 ${file.filename} 失败:`, error)
          return {
            name: file.filename.replace('.md', ''),
            type: 'file',
            path: file.path,
            filename: file.filename,
            lastModified: new Date()
          }
        }
      })
    )

    files.value = filesWithNames
  } catch (error) {
    console.error('读取目录失败:', error)
    // 如果读取目录失败，使用默认文件
    files.value = [
      { name: 'README', type: 'file', path: 'README.md', filename: 'README.md', lastModified: new Date() },
      { name: '示例', type: 'file', path: '示例.md', filename: '示例.md', lastModified: new Date() }
    ]
  }
}

const selectFile = (file) => {
  emit('file-selected', file)
}

const isActiveFile = (file) => {
  // 这里需要父组件传递当前文件，暂时不实现
  return false
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 右键菜单相关函数
const showContextMenu = (event, file) => {
  event.preventDefault()
  selectedFileForMenu.value = file
  contextMenuX.value = event.clientX
  contextMenuY.value = event.clientY
  contextMenuVisible.value = true
}

const closeContextMenu = () => {
  contextMenuVisible.value = false
  selectedFileForMenu.value = null
}

const deleteFile = async (file) => {
  closeContextMenu()
  if (!file) return

  try {
    const confirmed = await showConfirm({
      title: '确认删除',
      message: `确定要删除文件 "${file.name}" 吗？此操作不可恢复。`,
      type: 'danger',
      confirmText: '删除',
      cancelText: '取消'
    })

    if (confirmed) {
      // 使用electronAPI删除文件
      const result = await window.electronAPI.deleteFile(file.path)
      
      if (result.success) {
        // 从列表中移除文件
        files.value = files.value.filter(f => f.path !== file.path)
        
        // 通知父组件文件被删除
        emit('file-deleted', file)
        
        console.log(`已删除文件: ${file.name}`)
      } else {
        throw new Error(result.error)
      }
    }
  } catch (error) {
    console.error('删除文件失败:', error)
    alert('删除文件失败: ' + error.message)
  }
}

// 点击页面其他地方关闭右键菜单
const handleClickOutside = (event) => {
  if (!event.target.closest('.context-menu')) {
    closeContextMenu()
  }
}

const createNewFile = async () => {
  try {
    // 使用UUID生成文件名
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0
      const v = c === 'x' ? r : (r & 0x3 | 0x8)
      return v.toString(16)
    })
    const filename = `${uuid}.md`
    const filePath = `${defaultDir.value}/${filename}`;
    
    // 创建文件内容
    const content = `# 未命名文档

开始编写您的Markdown文档...
`;
    
    // 使用electronAPI创建文件
    const result = await window.electronAPI.createFile(filePath, content);
    
    if (result.success) {
      // 添加到文件列表
      const newFile = {
        name: '未命名文档',
        type: 'file',
        path: filePath,
        filename: filename,
        lastModified: new Date()
      }
      files.value.unshift(newFile)
      
      // 自动选中新创建的文件
      emit('file-selected', newFile)
      console.log(`已创建文件: ${filename}`)
    } else {
      throw new Error(result.error)
    }
  } catch (error) {
    console.error('创建文件失败:', error)
    alert('创建文件失败: ' + error.message)
  }
}

onMounted(async () => {
  try {
    const config = await window.electronAPI.config.get("file")
    console.log('配置文件:', config.data.defaultDirectory)
    defaultDir.value = config.data.defaultDirectory || ''
    await loadFilesFromDirectory()
  } catch (error) {
    console.error('初始化配置失败:', error)
    defaultDir.value = ''
    await loadFilesFromDirectory()
  }
  
  // 添加全局点击事件监听，用于关闭右键菜单
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  // 清理事件监听器
  document.removeEventListener('click', handleClickOutside)
})

// 暴露方法给父组件
const updateFiles = () => {
  loadFilesFromDirectory()
}
  

defineExpose({
  files,
  createNewFile,
  updateFiles
})
</script>

<style scoped>
.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 120px;
}

.context-menu-item {
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  transition: background-color 0.2s;
}

.context-menu-item:hover {
  background-color: #f5f5f5;
}

.context-menu-item.danger {
  color: #ff4d4f;
}

.context-menu-item.danger:hover {
  background-color: #fff1f0;
}


</style>